<?
session_start();

if ($_SERVER["REQUEST_METHOD"]=="POST")
{
require('./zip.lib.php');
$zipfile = new zipfile();
    if (!session_is_registered(MySBB_Admin_username)) {
     die();
    }


    $filename         = "MySmartBB";
    $filename        .= date("j-n-Y");

    if($_POST["type"]=="sql"){
        $filename        .= ".sql";
        header('Content-Type: application/octetstream');
    }elseif($_POST["type"]=="zip"){
        $filename        .= ".zip";
        header('Content-Type: application/x-zip');
    }else{
        $filename        .= ".sql.gz";
        header('Content-Type: application/x-zip');
    }



         header('Content-Disposition: filename="' . $filename . '"');
        $asfile="download";

        include("../includes/config.php");
    include("../includes/SmartSQL.php");

    $DB = new SmartSQL;
    $DB->setinfo($db_server,$db_username,$db_password,$db_name);
        $DB->sql_connect();
        $DB->sql_selectdb();

    $member_query    = $DB->sql_query("SELECT * FROM " . $db_prefix . "member WHERE username='" . $_COOKIE['MySBB_Admin_username'] . "' and password='" . $_COOKIE['MySBB_Admin_password'] . "'");
    $member_row      = $DB->sql_fetch_array($member_query);

    $groupper_query  = $DB->sql_query("SELECT * FROM " . $db_prefix . "group WHERE id='" . $member_row['usergroup'] . "'");
    $groupper_row    = $DB->sql_fetch_array($groupper_query);

    if ($groupper_row['admincp_database'] != 1) { die("المعذره .. هذه الميزه غير متاحه لك !"); }



                $crlf="\r\n";


      $dbname = $DB->db_name;
      $filesno = intval($_POST["filesno"]);

      $TablesArray = array();
         if($filesno=="" or filesno < 0){
             $filesno = "1";
         }
                $dump_buffer="";

                $tables = $DB->sql_query("show tables from $dbname");
                $num_tables = $DB->sql_num_rows($tables);

                if($num_tables == 0)
                {
                        echo "# لم يتم العثور على جداول";
                        exit;
                }

                $dump_buffer.= "# برنامج منتدى MySmartBB $crlf";
                $dump_buffer.= "# تم اخذ هذه النسخه بتاريخ :$crlf";
                $dump_buffer.= "# ".date("F j, Y, g:i a")."$crlf";
                $dump_buffer.= "# قاعدة البيانات : $dbname$crlf";

                $i = 0;
                while($i < $num_tables)
                {
                        $table = mysql_tablename($tables, $i);
                        IF ($_POST[$table."2"] == "1"){
                            if($_POST["multi"]=="3"){
                                $dump_buffer = "";
                            }
                                $dump_buffer.= "#--------------------------------------------------------$crlf";
                                $dump_buffer.= "$crlf#$crlf";
                                $dump_buffer.= "# النظم الهيكلية للجدول '$table'$crlf";
                                $dump_buffer.= "#$crlf$crlf";
                                $db = $table;
                                $dump_buffer.= get_table_def($table, $crlf,$dbname).";$crlf";
                                $dump_buffer.= "$crlf#$crlf";
                                $dump_buffer.= "# استرجاع بيانات الجدول '$table'$crlf";
                                $dump_buffer.= "#$crlf$crlf";
                                $tmp_buffer="";
                                get_table_content($dbname, $table, 0, 0, 'my_handler', $dbname);
                                $dump_buffer.=$tmp_buffer;
                                $TablesArray[$i]["dump"] = $dump_buffer;
                                $TablesArray[$i]["name"] = $table;
                         }
                        $i++;
                        $dump_buffer.= "$crlf";
                }
                if($_POST["multi"]=="3"){
                    $count = count($TablesArray);
                    for($i=0; $i <= $count; $i++){
                        $zipfile -> addFile($TablesArray[$i]["dump"],
                                               $TablesArray[$i]["name"].".sql");
                    }
                 echo $zipfile -> file();
                }elseif($filesno=="1" and $_POST["multi"]!="3"){
                if($_POST["type"]=="zip"){
                    $zipfile -> addFile($dump_buffer, "MySmartBB.sql");
                    echo $zipfile -> file();
                }
                elseif($_POST["type"]=="gz")
                {
                    if (@function_exists('gzencode')) {
                    echo gzencode($dump_buffer);
                    }
                }
                else
                {
                echo $dump_buffer;
                }
                }else{
                    $new_buffer = explode("$crlf" , $dump_buffer);
                    $count = count($new_buffer);
                    $lineno = ceil($count / $filesno);
                    $x = 0;
                    $s = 1;
                    $buffer = "";
                    for($i=0; $i <= $count; $i++){
                    $buffer .=  $new_buffer[$i];
                    $buffer .= $crlf;
                    ++$x;
                        if($x==$lineno or $i>=$count){
                           $zipfile -> addFile($buffer, "MySmartBB".$s.".sql");
                           $buffer = "";
                           $x = 0;
                           ++$s;
                        }
                    }
                  echo $zipfile -> file();
                }
                exit;
}
else
{
        include('common.php');
    if (!session_is_registered(MySBB_Admin_username)) {
     die();
    }

/*************************************************************************/

    if ($groupper_row['admincp_database'] != 1)
    {
         die("المعذره .. هذه الميزه غير متاحه لك !");
    }

/*************************************************************************/

      $table_row = array();
      $TablesCheck  = "";

      $dbname = $DB->db_name;
         $Sql = "SHOW TABLE STATUS FROM " .$dbname;
         $Result = $DB->sql_query($Sql);
         $Siize      = intval($Siize);
         $Siize = 0;
         while ($Data = mysql_fetch_array($Result))
                {
                 $Size = $Data["Data_length"] + $Data["Index_length"];
                     $Data["SizeKB"]=ceil($Size/1024);
                $TablesCheck .= 'SaTable.'.$Data["Name"] .'2.checked = SaTable.SelectAllSa.checked;
                ';
                $Siize = $Siize + $Data["SizeKB"];
                $table_row[] = $Data;

                $Smarty->assign('table_row',$table_row);
                $DBSize=$DBSize+$Size;
                $DBRows=$DBRows+$Data[Rows];
            }
            $Sele  = "SelectAll = function(){";
            $Sele .= $TablesCheck;
            $Sele .= "}";
            $Smarty->assign('Siize',$Siize);
            $Smarty->assign('Sele',$Sele);
            $SF->Make_cplink_path('نسخة احتياطية');
            $Smarty->display('backup.tpl');
}
        function get_table_def($table, $crlf,$dbname)
        {
                IF ($_POST["SaDrop"] == "1"){
                $schema_create = "DROP TABLE IF EXISTS $table;$crlf";
                }
                $db = $table;

                $schema_create .= "CREATE TABLE $table (";

                $result = mysql_query("SHOW FIELDS FROM " .$dbname."."
                . $table) or die();
                while($row = mysql_fetch_array($result))
                {
                        $schema_create .= "   $row[Field] $row[Type]";

                        if(isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0"))
                                $schema_create .= " DEFAULT '$row[Default]'";
                        if($row["Null"] != "YES")
                                $schema_create .= " NOT NULL";
                        if($row["Extra"] != "")
                                $schema_create .= " $row[Extra]";
                        $schema_create .= ",";
                }
                $schema_create = ereg_replace(",$", "", $schema_create);
                $result = mysql_query("SHOW KEYS FROM " .$dbname."." .
                $table) or die();
                while($row = mysql_fetch_array($result))
                {
                        $kname=$row['Key_name'];
                        $comment=(isset($row['Comment'])) ? $row['Comment'] : '';
                        $sub_part=(isset($row['Sub_part'])) ? $row['Sub_part'] : '';

                        if(($kname != "PRIMARY") && ($row['Non_unique'] == 0))
                                $kname="UNIQUE|$kname";

                        if($comment=="FULLTEXT")
                                $kname="FULLTEXT|$kname";
                         if(!isset($index[$kname]))
                                 $index[$kname] = array();

                        if ($sub_part>1)
                         $index[$kname][] = $row['Column_name'] . "(" . $sub_part . ")";
                        else
                         $index[$kname][] = $row['Column_name'];
                }

                while(list($x, $columns) = @each($index))
                {
                         $schema_create .= ",";
                         if($x == "PRIMARY")
                                $schema_create .= "   PRIMARY KEY (";
                         elseif (substr($x,0,6) == "UNIQUE")
                                $schema_create .= "   UNIQUE " .substr($x,7)." (";
                         elseif (substr($x,0,8) == "FULLTEXT")
                                $schema_create .= "   FULLTEXT ".substr($x,9)." (";
                         else
                                $schema_create .= "   KEY $x (";

                        $schema_create .= implode($columns,", ") . ")";
                }

                $schema_create .= ")";
                if(get_magic_quotes_gpc()) {
                  return (stripslashes($schema_create));
                } else {
                  return ($schema_create);
                }
        }
        function get_table_content($db, $table, $limit_from = 0, $limit_to = 0,$handler)
        {
                // Defines the offsets to use
                if ($limit_from > 0) {
                        $limit_from--;
                } else {
                        $limit_from = 0;
                }
                if ($limit_to > 0 && $limit_from >= 0) {
                        $add_query  = " LIMIT $limit_from, $limit_to";
                } else {
                        $add_query  = '';
                }

                get_table_content_fast($db, $table, $add_query,$handler);

        }

        function get_table_content_fast($db, $table, $add_query = '',$handler)
        {
                $result = mysql_query('SELECT * FROM ' . $db . '.' . $table . $add_query)
or die();
                if ($result != false) {

                        @set_time_limit(1200); // 20 Minutes

                        // Checks whether the field is an integer or not
                        for ($j = 0; $j < mysql_num_fields($result); $j++) {
                                $field_set[$j] = mysql_field_name($result, $j);
                                $type          = mysql_field_type($result, $j);
                                if ($type == 'tinyint' || $type == 'smallint' || $type == 'mediumint' || $type == 'int' ||
                                        $type == 'bigint'  ||$type == 'timestamp') {
                                        $field_num[$j] = true;
                                } else {
                                        $field_num[$j] = false;
                                }
                        } // end for

                        // Get the scheme
                        if (isset($GLOBALS['showcolumns'])) {
                                $fields        = implode(', ', $field_set);
                                $schema_insert = "INSERT INTO $table ($fields) VALUES (";
                        } else {
                                $schema_insert = "INSERT INTO $table VALUES (";
                        }

                        $field_count = mysql_num_fields($result);

                        $search  = array("\x0a","\x0d","\x1a"); //\x08\\x09, not required
                        $replace = array("\\n","\\r","\Z");


                        while ($row = mysql_fetch_row($result)) {
                                for ($j = 0; $j < $field_count; $j++) {
                                        if (!isset($row[$j])) {
                                                $values[]     = 'NULL';
                                        } else if (!empty($row[$j])) {
                                                // a number
                                                if ($field_num[$j]) {
                                                        $values[] = $row[$j];
                                                }
                                                // a string
                                                else {
                                                        $values[] = "'" . str_replace($search, $replace, addslashes($row[$j])) . "'";
                                                }
                                        } else {
                                                $values[]     = "''";
                                        } // end if
                                } // end for

                                $insert_line = $schema_insert . implode(',', $values) . ')';
                                unset($values);

                                // Call the handler
                                $handler($insert_line);
                        } // end while
                } // end if ($result != false)

                return true;
        }


        function my_handler($sql_insert)
        {
                global $crlf, $asfile;
                global $tmp_buffer;

                if(empty($asfile))
                        $tmp_buffer.= htmlspecialchars("$sql_insert;$crlf");
                else
                        $tmp_buffer.= "$sql_insert;$crlf";
        }



        function faqe_db_error()
        {
                return mysql_error();
        }



        function faqe_db_insert_id($result)
        {
                return mysql_insert_id($result);
        }
?>